# %% import
from langchain.chains import ConversationChain
from langchain.chains.conversation.memory import (
    ConversationBufferMemory, ConversationSummaryMemory, ConversationBufferWindowMemory
)
from langchain_openai import OpenAI
import streamlit as st
from streamlit_chat import message

# 创建session, 保存conversation
if 'conversation' not in st.session_state:
    st.session_state['conversation'] = None
# 创建session, 保存历史消息
if 'messages' not in st.session_state:
    st.session_state['messages'] = []
if 'API_Key' not in st.session_state:
    st.session_state['API_Key'] = ''

# %%
st.set_page_config(page_title="Chat GPT Clone", page_icon=":robot_face:")
st.markdown("<h1 style='text-align: center;'>How can I assist you? </h1>", unsafe_allow_html=True)

st.sidebar.title("😎")
# 侧边栏的输入框用来接收key
# api_key = st.sidebar.text_input("What's your API key?", type="password")
st.session_state['API_Key'] = st.sidebar.text_input("What's your API key?", type="password")
# api_base = st.sidebar.text_input("What's your API base?", type="default")
# 设计: 当我们点击这个按钮, 将会保存对话摘要
summarise_button = st.sidebar.button("Summarise the conversation", key='summarise')
# 点击按钮
if summarise_button:
    summarise_placeholder = st.sidebar.write("Nice chatting with you my friend ❤:\n\n" +
                                             st.session_state['conversation'].memory.buffer)

# %% env
import os

# os.environ['OPENAI_API_KEY'] = ""
# os.environ['OPENAI_API_BASE'] = ""
import dotenv

dotenv.load_dotenv()


# %% model
def get_response(userInput, api_key):
    # 如果没有会话, 则创建会话, 防止每次调用都重新创建, 导致清空之前的记录
    if st.session_state['conversation'] is None:
        # llm = OpenAI(temperature=0, model_name='gpt-4')
        llm = OpenAI(temperature=0, api_key=api_key)

        # conversation
        st.session_state['conversation'] = ConversationChain(
            llm=llm,
            verbose=True,
            memory=ConversationSummaryMemory(llm=llm)
        )

    res = st.session_state['conversation'].predict(input=userInput)

    return res


# %%
# 存放回复
response_container = st.container()
# 存放用户的输入
container = st.container()

# 提交container后, container被挤到下方, 原本的位置在响应结束后变为response container, 内容为ai的回答
with container:
    # clear_on_submit 提交会清空内容
    with st.form(key='my_form', clear_on_submit=True):
        user_input = st.text_area("Your question goes here:", key='input', height=100)
        submit_btn = st.form_submit_button('Send')
        if submit_btn:
            # 保存用户输入到历史信息
            st.session_state['messages'].append(user_input)
            answer = get_response(user_input, st.session_state['API_Key'])
            # 保存AI回复到历史信息
            st.session_state['messages'].append(answer)
            # 显示历史消息 到 container
            # st.write(st.session_state['messages'])

            # 回显
            with response_container:
                # st.write(answer)
                for i in range(len(st.session_state['messages'])):
                    # from streamlit_chat import message
                    if (i % 2) == 0:
                        message(st.session_state['messages'][i], is_user=True, key=str(i) + '_user')
                    else:
                        message(st.session_state['messages'][i], key=str(i) + '_AI')
